<template>
  <section class="userInfo">
    <a-form
      :form="form"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 12 }"
      @submit="handleSubmit"
    >
      <a-form-item label="姓名" required>
        <a-input v-model="form.name" />
      </a-form-item>
      <a-form-item label="手机号码" required>
        <a-input v-model="form.phone" />
      </a-form-item>
      <a-form-item label="头像">
        <a-upload
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :action="uploadUrl"
          :before-upload="beforeUpload"
          @change="handleChange"
          :headers="headers"
        >
          <img v-if="form.header_img" :src="form.header_img" alt="avatar" />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
        <a-button type="primary" html-type="submit" :loading="updating"
          >保存修改</a-button
        >
      </a-form-item>
    </a-form>
  </section>
</template>
<script>
import { updateUserInfo } from '@/services/user';
import { mapMutations, mapState } from 'vuex';
import { UPLOADFILE } from '@/services/api';
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  data() {
    return {
      form: {},
      loading: false,
      imageUrl: '',
      uploadUrl: '',
      updating: false,
      headers: '',
    };
  },

  created() {
    this.headers = {
      authorization: JSON.parse(localStorage.getItem('user')).token,
    };
  },
  mounted() {
    this.form = JSON.parse(localStorage.getItem('user'));
    this.uploadUrl = UPLOADFILE;
  },

  methods: {
    ...mapMutations('account', ['setUser']),

    // 保存
    async handleSubmit(e) {
      e.preventDefault();
      if (!this.form.name || !this.form.phone) {
        this.$message.error(`请填写${this.form.name ? '手机号码' : '用户名'}`);
        return;
      }
      if (!this.form.phone.match(/^1[3456789]\d{9}$/)) {
        this.$message.error('请填写正确手机号码');
        return;
      }

      this.updating = true;
      try {
        const res = await updateUserInfo(this.form);
        await this.$emit('cancel');
        await this.$message.success(res.msg);
        await this.setUser(res.result);
        this.updating = false;
      } catch (error) {
        this.updating = false;
        this.$message.error(error.msg);
      }
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, () => {
          this.form.header_img = info.file.response.path;
          this.loading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('头像上传仅支持JPEG和PNG格式喔!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片要小于2MB喔!');
      }
      return isJpgOrPng && isLt2M;
    },
  },
  computed: {
    ...mapState('account', ['user']),
  },
};
</script>
<style lang="scss" scoped>
.userInfo .ant-form {
  .ant-upload {
    width: 128px !important;
    height: 128px !important;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }
  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
}
</style>
